package com.dudu.controller;

import com.dudu.exception.ErrorCode;
import com.dudu.exception.ParamsInvalidException;
import com.dudu.util.FastJsonUtil;
import com.dudu.util.WebResponse;
import com.dudu.util.WebResponseHelper;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by dudu on 16/8/5.
 */
@Slf4j
public class BaseController extends ResponseEntityExceptionHandler {


    @ExceptionHandler(Exception.class)
    protected void handleExcption(HttpServletResponse response, Exception e) {
        response.setContentType("application/json;charset=utf-8");
        WebResponse res;
        if(e instanceof ParamsInvalidException){
            res = WebResponseHelper.error(ErrorCode.PARAMS_ERROR);
            response.setStatus(ErrorCode.PARAMS_ERROR.getCode());
        }else {
            res = WebResponseHelper.error(ErrorCode.SYSTEM_ERROR);
            response.setStatus(ErrorCode.SYSTEM_ERROR.getCode());
            log.error("REST Exception :"+e.getMessage(),e);
        }

        PrintWriter writer=null;

        try {
            writer=response.getWriter();
            writer.print(FastJsonUtil.bean2json(res));
        } catch (IOException ex) {
            //
        } finally {
            if(writer!=null){
                writer.flush();
                writer.close();
            }
        }
    }


}
